//
//  LSListeningController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSResPackageController.h"
#import "LSFtpManager.h"
#import "LSListenQuesView.h"
#import "LSModelQues.h"
#import "LSReadQuesView.h"
#import "LSResultView.h"
#import "KZTimerView.h"
#import "KZAlertView.h"
#import "LSResPackSaveManager.h"
#import "LSWrongCheckViewController.h"
#import "LSResListManager.h"
#import "LSResFirstController.h"
#import "LSQuesView.h"


#import "LSListenNewQuesView.h"
#import "KZIndexProgressView.h"
#import "KZTestResultVC.h"
#import "LSReadNewQuesView.h"


@interface LSResPackageController ()<LSListenQuesViewDelegate,LSReadQuesViewDelegate,LSListenNewQuesViewDelegate,LSReadNewQuesViewDelegate,UIPageViewControllerDelegate,UIPageViewControllerDataSource>

@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,assign) NSString *currentFileName;
@property (nonatomic,strong) LSModelQues *quesModel;

/*用来保存全部试题作答记录*/
@property (nonatomic,strong) NSMutableDictionary *allAnswerDict;
/*保存全部试题正确率记录*/
@property (nonatomic,strong) NSMutableDictionary *allRateDict;
/*全部试题model*/
@property (nonatomic,strong) NSMutableArray *allQuesModels;

/*时间*/
@property (nonatomic,strong) KZTimerView *timeView;
//@property (nonatomic,assign) NSInteger second;
@property (nonatomic,strong) NSDate *dateStart;
@property (nonatomic,strong) NSDate *dateEnd;
@property (nonatomic,strong) NSDate *allstartDate;
/*当前answerDict*/
@property (nonatomic,strong) NSMutableDictionary *currentDict;

/**
 进度表示
 */
@property (nonatomic,strong) KZIndexProgressView *progressView;

@property (nonatomic,assign) NSInteger index;

@property (nonatomic,assign) BOOL isSubmitLast;//表示最后一题是否提交

@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,strong) NSMutableArray *vcArray;
@property (nonatomic,strong) LSResContentVC *pendingViewController;

/*白色遮罩*/
@property (nonatomic,strong) UIView *backwhiteView;

@end

@implementation LSResPackageController

- (UIView *)backwhiteView {
    if (!_backwhiteView) {
        _backwhiteView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kWidth, kHeight-kBottomPadding)];
        _backwhiteView.backgroundColor = [UIColor whiteColor];
    }
    return _backwhiteView;
}

- (void)setModel:(LSModelLSResList *)model {

    _model = model;
    _allAnswerDict = [[NSMutableDictionary alloc] init];
    _allRateDict = [[NSMutableDictionary alloc] init];
    _allQuesModels = [NSMutableArray array];
  
    for (NSInteger i = 0; i<self.model.ResItemList.count; i++) {
        LSResItem *item = self.model.ResItemList[i];
        [_allRateDict setObject:@(item.CorrectRate) forKey:[NSString stringWithFormat:@"%ld",item.Index]];
    }
    
    for (NSInteger i = 0; i<self.model.ResItemList.count; i++) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        LSResItem *item = self.model.ResItemList[i];
        for (NSInteger j = 0; j<item.StuAnswer.count; j++) {
          LSstuAns *stuans = item.StuAnswer[j];
          [dict setObject:stuans.StuAnswer forKey:[NSString stringWithFormat:@"%ld",stuans.ChildIndex]];
        }
        [_allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",i+1]];
    }
    NSLog(@"[0]%@",_allAnswerDict);
    
}

// 如果之前某个包没做完，则继续做该包
- (void)welcomeBack {
    
    NSString *text;
    NSString *subText;
    if ([_model.PackageTypeID isEqualToString:@"SE"]) {
        text = [NSString stringWithFormat:@"欢迎回来~\n据小鸽记录，您将继续听力选择第%li题的训练", _currentIndex + 1];
        subText = [NSString stringWithFormat:@"听力选择第%li题", _currentIndex + 1];
    } else {
        text = [NSString stringWithFormat:@"欢迎回来~\n据小鸽记录，您将继续朗读训练第%li题的训练", _currentIndex + 1];
        subText = [NSString stringWithFormat:@"朗读训练第%li题", _currentIndex + 1];
    }
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.orangeColor range:[text rangeOfString:subText]];
    
    // 跳了很多级时有可能出现在上一级那里(bug)

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        KZAlertView *alert = [KZAlertView new];
        WeakObj(self);
        [alert showWithTitle:@"温馨提示" subtitle:attrStr.copy submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
            [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
            
        } click:^(NSInteger index) {
            
            if (index==0) {
               // [selfWeak loadData];
                [self.view addSubview:self.backwhiteView];
                [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
                [self loadAllFtpResData];
                selfWeak.timeView.time = selfWeak.model.PackageTotalDuration;
            }
            
        } destroyAtClickIndex:@[@0]];
    });
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initContentViewController];
    //在页面上，显示UIPageViewController对象的View
    [self addChildViewController:self.pageViewController];
    [self.view addSubview:self.pageViewController.view];
    UIScrollView *pageVCSrollView = [self findScrollView];
    pageVCSrollView.scrollEnabled = NO;
    
    
    if (!self.progressView ) {
        KZIndexProgressView *progressView = [[KZIndexProgressView alloc] init];
        progressView.totalIndex = _model.ResItemList.count;
        progressView.index = _currentIndex+1;
        progressView.alpha = 0;
        self.progressView = progressView;
        [self.view addSubview:progressView];
        [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            if (@available(iOS 11.0, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.height.mas_equalTo(48);
                
            } else {
                make.top.equalTo(self.view).offset(0);
                make.height.mas_equalTo(48);
            }
        }];
    }

    NSInteger count = 0;
    for (NSInteger i = 0; i<_model.StuAnswer.count; i++) {
        LSstuAns *stuans = _model.StuAnswer[i];
        if (![stuans.StuAnswer isEqualToString:@""]) {
            count = count+1;
        }
    }
    
    if(_model.CurrentQueIndex==0) {
        _model.CurrentQueIndex = 1;
    }
    
    CGFloat correct = _model.ResItemList[_model.CurrentQueIndex-1].CorrectRate;
    
//    _model.CurrentQueSubmitCount = 0;//测试用代码需要删除
//    _model.CurrentQueIndex = 1;//测试用代码需要删除
    
//    if (count==_model.StuAnswer.count && count!=0) {
//        _currentIndex = _model.CurrentQueIndex;//下一题
//    } else
    if([_model.PackageTypeID isEqualToString:@"SE"] && correct>=LS_System.listenScore/100.0){
        _currentIndex = _model.CurrentQueIndex;//下一题
    } else if([_model.PackageTypeID isEqualToString:@"Spn"] && correct>=LS_System.readScore/100.0) {
        _currentIndex = _model.CurrentQueIndex;//下一题
    } else if (_model.CurrentQueSubmitCount>0) {
        _currentIndex = _model.CurrentQueIndex;//下一题
    } else {
        _currentIndex = _model.CurrentQueIndex-1;//本题
        self.currentDict = [[NSMutableDictionary alloc] init];
        for (NSInteger i = 0; i<_model.StuAnswer.count; i++) {
            LSstuAns *stuans = _model.StuAnswer[i];
            
            if (![stuans.StuAnswer isEqualToString:@""] ) {
                [self.currentDict setObject:stuans.StuAnswer forKey:[NSString stringWithFormat:@"%ld",stuans.ChildIndex]];
            }
        }
//        if (self.currentDict.count==_model.StuAnswer.count) {
//            [self.currentDict removeAllObjects];
//        }
    }
    
    NSString *text = @"";
//    if ([_model.PackageTypeID isEqualToString:@"SE"]) {
//        text = [NSString stringWithFormat:@"%@听力训练",text];
//    } else if ([_model.PackageTypeID isEqualToString:@"Sp"]||[_model.PackageTypeID isEqualToString:@"Spn"]) {
//        text = [NSString stringWithFormat:@"%@朗读训练",text];
//    }
    if (_model.PackageStage==1) {
       // text = [NSString stringWithFormat:@"慢速%@",text];
        text = @"第1关";
    } else if (_model.PackageStage==2) {
       // text = [NSString stringWithFormat:@"中速%@",text];
        text = @"第2关";
    } else if (_model.PackageStage==3) {
      //  text = [NSString stringWithFormat:@"快速%@",text];
        text = @"第3关";
    }

    self.title = text;
    [self addBYItemviews:@[@"LS-nav_back"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeLeft];

    //顶部计时器
    [self setupTimeView];
    
    if (_currentIndex != 0) {
        //欢迎继续作答界面
        [self welcomeBack];
    } else {
        //新界面
        [self.view addSubview:self.backwhiteView];
        [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
        
        [self loadAllFtpResData];
        self.timeView.time = self.model.PackageTotalDuration;
    }

   // self.second = 0;
    self.dateStart = [NSDate date];
    self.allstartDate = [NSDate date];
}

- (void)setupTimeView {
    _timeView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    WeakObj(self);
    _timeView.clickBlock = ^(BOOL isPause){
        
        if (isPause) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
            //判断提示文字
            NSMutableAttributedString *muattr = nil;
           // LSQuesView *quesView = [selfWeak.view viewWithTag:10000+selfWeak.currentIndex];
            LSResContentVC *vc = selfWeak.vcArray[selfWeak.currentIndex];
            LSBaseQuesView *quesView = vc.view.subviews.firstObject;
            
            if (quesView.pasueState!=LSQuesPauseType_Recording || [selfWeak.model.PackageTypeID isEqualToString:@"SE"]) {
                NSString *text = @"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~";
                NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                                   initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
                muattr = attr;
            } else if (quesView.pasueState == LSQuesPauseType_Recording) {
//                NSString *text = @"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n注意:若点击继续训练，本题将重新开始录音";
//                NSRange range = [text rangeOfString:@"注意:若点击继续训练，本题将重新开始录音"];
//                NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
//                                                   initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
//                [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
                NSString *text = @"哎呀，正在录音被你打断了，一会儿得重新开始了呦";
                NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                                   initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
                muattr = attr;
            }
            
            [selfWeak reset:muattr];
            
        }
    };
    [self addCustomItemviews:@[_timeView] position:ByNavigationItemPositionModeRight];
}

//休息一下
- (void)reset:(NSMutableAttributedString*)muattr {
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:muattr submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
        
    } click:^(NSInteger index) {
        // 点击继续
        if (index == 0) {
            
            [self.timeView resume];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeResume" object:nil];
        }
        
    } destroyAtClickIndex:@[@0]];
}


- (void)back {
    if (_currentIndex==self.model.ResItemList.count) {
        [self.timeView stop];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
        UIView *quesView = [self.view viewWithTag:10000+_currentIndex];
        [[NSNotificationCenter defaultCenter] removeObserver:quesView];
        quesView = nil;

        [self deleteAllUnZip];

        [self.navigationController popToRootViewControllerAnimated:YES];
        
    } else {
        //先暂停
        [self.timeView pause];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimePause" object:nil];
        
        //判断提示文字
        NSMutableAttributedString *muattr;
       // LSQuesView *quesView = [self.view viewWithTag:10000+_currentIndex];
        LSResContentVC *vc = self.vcArray[_currentIndex];
        LSBaseQuesView *quesView = vc.view.subviews.firstObject;
        
        if (quesView.pasueState!=LSQuesPauseType_Recording || [_model.PackageTypeID isEqualToString:@"SE"]) {
            NSString *text = [NSString stringWithFormat:@"你确定要退出\n%@\n\n",self.title];
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                               initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
            muattr = attr;
        } else if (quesView.pasueState==LSQuesPauseType_Recording) {
//            NSString *text = [NSString stringWithFormat:@"你确定要退出\n%@\n\n注意:若点击继续训练，本题将重新开始录音",self.title];
//            NSRange range = [text rangeOfString:@"注意:若点击继续训练，本题将重新开始录音"];
//            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
//                                               initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
//            [attr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]
                                               initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
            muattr = attr;
        }
            
        // 弹框提示
        KZAlertView *alert = [KZAlertView new];
        WeakObj(self);
        [alert showWithTitle:@"温馨提示" subtitle:muattr submitTypes:@[@0, @1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
            
            [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
            [buttons.lastObject setTitle:@"继续训练" forState:UIControlStateNormal];
        } click:^(NSInteger index) {
            // 点击退出
            if (index == 0) {
                [selfWeak.timeView stop];
                selfWeak.timeView = nil;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
           
                LSResContentVC *vc = selfWeak.vcArray[_currentIndex];
                LSBaseQuesView *quesView = vc.view.subviews.firstObject;
                
                if ([quesView isKindOfClass:[LSListenNewQuesView class]]) {
                    
                    LSListenNewQuesView *newView = (LSListenNewQuesView*)quesView;
                    if(!newView.isReAnswer) {
                        [selfWeak backSave];
                        [[NSNotificationCenter defaultCenter] removeObserver:quesView];
                        quesView = nil;
                    }
                }
           
                if (selfWeak.currentIndex==selfWeak.model.ResItemList.count-1) {
                    [selfWeak deleteAllUnZip];
                    NSLog(@"删除全部下载内容");
                }

                [self.navigationController popToRootViewControllerAnimated:YES];
              
            }
            // 点击继续
            else {
                [selfWeak.timeView resume];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeResume" object:nil];
            }
            
        } destroyAtClickIndex:@[@0, @1]];
    }
}

- (void)backSave {
    
    if ([_model.PackageTypeID isEqualToString:@"SE"]) {
        LSResContentVC *vc = self.vcArray[_currentIndex];
        LSListenNewQuesView *quesView = vc.view.subviews.firstObject;
        if (quesView.isReAnswer==NO) {
            [self FinishAnswerQues:quesView.answerDict CorrectRate:0 IsSave:YES];
        }
    } else {
        
    }
}

- (void)deleteAllUnZip {
    for (NSInteger i = 0; i<_model.ResItemList.count; i++) {
        NSString *fileName = _model.ResItemList[i].QuesID;
        LSFtpManager *manager = [[LSFtpManager alloc] init];
        [manager deleteUnzip:fileName];
    }
    NSString *unzipPath = [NSString stringWithFormat:@"%@%@", NSHomeDirectory(),@"/Documents/record"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:unzipPath];
    for (NSString *name in enumerator) {
        [[NSFileManager defaultManager] removeItemAtPath:[unzipPath stringByAppendingPathComponent:name] error:nil];
    }
    NSLog(@"资源全部删除");
}

#pragma mark - 网络请求&ftp下载
- (void)loadAllFtpResData {
   
    LSResItem *item = _model.ResItemList[_index];
    NSString *ftpUrl = item.FtpUrl;
    NSArray *array = [ftpUrl componentsSeparatedByString:@"/"];
    NSString *currentFileName = [array.lastObject componentsSeparatedByString:@"."].firstObject;
    WeakObj(self);//
    LSFtpManager *manager = [[LSFtpManager alloc] init];
    [manager LS_ftpdownloadFileName:currentFileName Path:ftpUrl Success:^(NSDictionary *pathDict, NSArray *names) {
        
        NSLog(@"下载进度：%ld/%ld",selfWeak.index+1,selfWeak.model.ResItemList.count);
        //分析数据
        NSDictionary *xmlDic = [NSDictionary dictionaryWithXMLFile:pathDict[@"XML"]];
        
        LSQuestionType type;
        if ([_model.PackageTypeID isEqualToString:@"SE"]) {
            type = LSListeningTest;
        } else if ([_model.PackageTypeID isEqualToString:@"Sp"] || [_model.PackageTypeID isEqualToString:@"Spn"] ) {
            type = LSReadingTest;
        } else {
            type = LSFollowSpeakingTest;
        }
        
        NSString *addressPath = [pathDict[@"XML"] stringByReplacingOccurrencesOfString:[pathDict[@"XML"] componentsSeparatedByString:@"/"].lastObject withString:@""];
        LSModelQues *quesModel = [[LSModelQues alloc] initWithDict:xmlDic Type:type AddressPath:addressPath];
        [selfWeak.allQuesModels addObject:quesModel];
        
        selfWeak.index++;
        if (selfWeak.index < selfWeak.model.ResItemList.count ) {
            //下载下一个
            [selfWeak loadAllFtpResData];
            
        } else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                for (NSInteger i = _currentIndex; i<selfWeak.vcArray.count ; i++ ) {
                    LSResContentVC *vc= selfWeak.vcArray[i];
                    [selfWeak setUpUIwithFatherView:vc.view Index:i];
                }
//                LSResContentVC *vc= selfWeak.vcArray[_currentIndex];
//                [selfWeak setUpUIwithFatherView:vc.view Index:_currentIndex];
                [selfWeak jumpToControllerIndex:_currentIndex];
                
//                [MBProgressHUD hideHUDForView:selfWeak.view animated:YES];
//                [selfWeak.backwhiteView removeFromSuperview];
            });
        }
        
    } failuer:^(NSString *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"error:%@",error);
            [MBProgressHUD hideHUDForView:selfWeak.view animated:YES];
            [selfWeak.backwhiteView removeFromSuperview];
        });
    }];
}

#pragma mark - 创建视图
- (void)setUpUIwithFatherView:(UIView*)fatherView Index:(NSInteger)index{
    LSResItem *item = _model.ResItemList[_currentIndex];
    
    if([_model.PackageTypeID isEqualToString:@"SE"] || [_model.PackageTypeID isEqualToString:@"E"]) {//听力
        
        LSListenNewQuesView *quesView = [[LSListenNewQuesView alloc] initWithFrame:CGRectMake(0,48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.delegate = self;
        quesView.speedLayer = self.model.PackageStage;
        self.quesModel = self.allQuesModels[index];
        if ([_model.PackageTypeID isEqualToString:@"SE"]) {
            self.quesModel.ReadTime =  item.ReadTime;
            self.quesModel.WaitTime = item.WaitTime;
            self.quesModel.RecordTime = item.RecordTime;
        }
        if (index==_currentIndex) {
            quesView.answerDict = self.currentDict;
        }
        quesView.model = self.quesModel;
        [fatherView addSubview:quesView];
        
    } else if ([_model.PackageTypeID  isEqualToString:@"Spn"]) { //朗读
        
        LSReadNewQuesView *quesView = [[LSReadNewQuesView alloc] initWithFrame:CGRectMake(0,48,kWidth, kHeight-kBottomPadding-kNavgationBar-48)];
        quesView.delegate = self;
        quesView.speedLayer = self.model.PackageStage;
        self.quesModel = self.allQuesModels[index];
        self.quesModel.ReadTime =  item.ReadTime;
        self.quesModel.WaitTime = item.WaitTime;
        self.quesModel.RecordTime = item.RecordTime;
        quesView.model = self.quesModel;
        [fatherView addSubview:quesView];
    }
}

#pragma mark - 查看错题
- (void)enterWrongQuesVC {
    LSWrongCheckViewController *vc = [[LSWrongCheckViewController alloc] init];
    // vc.model = self.model;
    vc.allAnswerDict = self.allAnswerDict;
    NSLog(@"[4]%@",self.allAnswerDict);
    NSMutableArray *wrongQuesIndexArr = [NSMutableArray array];
    NSMutableArray *wrongQuesModelArr = [NSMutableArray array];
    NSMutableArray *typeIDArr = [NSMutableArray array];
    NSMutableArray *wrongQuesItemArr = [NSMutableArray array];
    for (NSInteger i = 0; i<self.allRateDict.count; i++) {
        
        NSNumber *rateNum = [self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        CGFloat rate = rateNum.floatValue;
        if ([_model.PackageTypeID isEqualToString:@"Sp"]||[_model.PackageTypeID isEqualToString:@"Spn"]||[_model.PackageID isEqualToString:@"Sq"]) {
            if (rate<LS_System.readScore*1.0/100.0) {
                NSLog(@"rate=%f %f",rate,LS_System.readScore*1.0/100.0);
                [wrongQuesIndexArr addObject:@(i)];
                //[wrongQuesModelArr addObject:self.allQuesModels[i]];
                [typeIDArr addObject:_model.PackageTypeID];
                [wrongQuesItemArr addObject:_model.ResItemList[i]];
            }
        } else {
            if (rate<LS_System.listenScore*1.0/100.0) {
                NSLog(@"rate=%f %f",rate,LS_System.listenScore*1.0/100.0);
                [wrongQuesIndexArr addObject:@(i)];
                //[wrongQuesModelArr addObject:self.allQuesModels[i]];
                [typeIDArr addObject:_model.PackageTypeID];
                [wrongQuesItemArr addObject:_model.ResItemList[i]];
            }
        }
        
    }
    vc.wrongQuesIndexArr = wrongQuesIndexArr;
    vc.wrongQuesModelArr = wrongQuesModelArr;
    //vc.model = _model;
    vc.wrongQuesItemArr = wrongQuesItemArr;
    vc.typeIDarr = typeIDArr;

    [self push:vc];
}

- (void)retrunShowComplteView {
    /////
}

#pragma mark - LSListenQuesViewDelegate
- (void)FinishAnswerQues:(NSDictionary *)answerDict CorrectRate:(CGFloat)correctRate IsSave:(BOOL)isSave{
    if (!isSave && _currentIndex==self.model.ResItemList.count-1) {
        _isSubmitLast = YES;
    }
    //保存当前currentIndex作答记录
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
    [self.allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    
    NSLog(@"[3]%@",self.allAnswerDict);
    
    if (correctRate>=LS_System.listenScore/100.0) {
        [self.allRateDict setObject:@(correctRate) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    } else {
        [self.allRateDict setObject:@(correctRate) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    }
    NSInteger count  = 0;
    NSInteger isPass = 0;
    for (NSInteger i = 0; i<self.model.ResItemList.count; i++) {
        CGFloat rate = ((NSNumber*)[self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]]).floatValue;
        NSLog(@"LS_System.listenScore*1.0/100.0=%f",LS_System.listenScore*1.0/100.0);
        if (rate>=LS_System.listenScore*1.0/100.0) {
            count = count+1;
        }
    }
    if (count == _model.ResItemList.count && count!=0) {
        isPass = 1;
    }
    NSInteger State = 2;
    if (_currentIndex == self.model.ResItemList.count-1) {
        State = 3;
        NSLog(@"self.allRateDict = %@",self.allRateDict);
//        //测试用
//        isPass = 1;
    }
    if (isSave==YES) {
        State = 1;
    }
    
    NSLog(@"//////进行保存");
    NSMutableArray *stuAnsArr = [NSMutableArray array];
    self.quesModel = self.allQuesModels[_currentIndex];
    for (NSInteger i = 0;i<self.quesModel.ChildList.count;i++) {
        NSString *stuAnswer = [answerDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        if(stuAnswer == nil) {
            stuAnswer = @"";
        }
        LSChild *child = self.quesModel.ChildList[i];
        NSDictionary *stuAns = @{@"ChildIndex":@(i+1),
                                 @"StuAnswer":stuAnswer,
                                 @"Answer":child.ChildAnswer
                                 };
        [stuAnsArr addObject:stuAns];
    }
    
    self.dateEnd = [NSDate date];
    NSInteger dur = [self.dateEnd timeIntervalSince1970]-[self.dateStart timeIntervalSince1970];
    NSInteger allDur = [self.dateEnd timeIntervalSince1970]-[self.allstartDate timeIntervalSince1970]+self.timeView.time;
    LSResItem *item = _model.ResItemList[_currentIndex];
    
    NSDictionary *saveParam = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                                @"SchoolID":KGetUserDefaults(@"SchoolID"),
                                @"StuID":DR_UserInfo.UserID,
                                @"QuesID":item.QuesID,
                                @"TypeID":_model.PackageTypeID,
                                @"PackageID":_model.PackageID,
                                @"TotalItemCount":@(self.quesModel.TotalItemCount),
                                @"AnswerItemCount":@(answerDict.count),
                                @"CorrectRate":@(correctRate),
                                @"Score":@{},
                                @"StuAnswer":stuAnsArr,
                                @"Duration":@(dur),
                                @"State":@(State),
                                @"IsPassed":@(isPass),
                                @"PackageTotalDuration":@(allDur),
                                @"Stage":@(_model.PackageStage),
                                @"ImportKlgCode":item.ImportKlgCode?item.ImportKlgCode:@""
                                };
    LSResPackSaveManager *manager = [[LSResPackSaveManager alloc] init];
    manager.requestParam = saveParam;
    [manager requestSaveResPackWithCompltionSuccess:^(NSString *success) {

    } failuer:^(NSString *failure) {

    }];
    
}

- (void)willEnterNextQues {
    NSLog(@"/////进入下一题");
    [self.currentDict removeAllObjects];
    self.dateStart = [NSDate date];
    [UIView animateWithDuration:0.3 animations:^{
        
        [self.view layoutIfNeeded];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
        
    } completion:^(BOOL finished) {

        _currentIndex = _currentIndex + 1;
        if(_currentIndex<_model.ResItemList.count) {
            
            [self jumpToControllerIndex:_currentIndex];
            
        } else if (_currentIndex == _model.ResItemList.count) {
            
            [self.timeView stop];
            KZTestResultVC *vc = [KZTestResultVC new];
            NSInteger count = 0;
            for (NSInteger i = 0; i<self.allRateDict.count; i++) {
                
                CGFloat rate = ((NSNumber*)[self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]]).floatValue;
                
                if ([_model.PackageTypeID isEqualToString:@"Sp"]||[_model.PackageTypeID isEqualToString:@"Spn"]||[_model.PackageTypeID isEqualToString:@"Sq"]) {
                    
                    if (rate>=LS_System.readScore*1.0/100.0) {
                        NSLog(@"(LS_System.readScore*1.0/100.0)=%f",LS_System.readScore*1.0/100.0);
                        count = count+1;
                    }
                    
                } else {
                    
                    if (rate>=LS_System.listenScore*1.0/100.0) {
                        NSLog(@"(LS_System.listenScore*1.0/100.0)=%f",LS_System.listenScore*1.0/100.0);
                        count = count+1;
                    }
                }
            }
            
            BOOL isLastTure = NO;
            if (_model.PackageStage==3 && count==self.allRateDict.count) {
                isLastTure = YES;
            }
            
            vc.resultDic = @{@"TrueCount":@(count),
                             @"WrongCount":@(self.allRateDict.count-count),
                             @"time":@(_timeView.time),
                             @"isLastTure":@(isLastTure),
                             @"PackageTypeID":_model.PackageTypeID
                             };
            vc.wrongCheckModel = [self getModelWrongCheckInfo];
            vc.reslistModel = _model;
            
            [self.navigationController pushViewController:vc animated:true];
            
            
        }
    }];
}

- (LSModelWrongCheckInfo*)getModelWrongCheckInfo {
    
    NSMutableArray *wrongQuesIndexArr = [NSMutableArray array];
    NSMutableArray *wrongQuesModelArr = [NSMutableArray array];
    NSMutableArray *typeIDArr = [NSMutableArray array];
    NSMutableArray *wrongQuesItemArr = [NSMutableArray array];
    for (NSInteger i = 0; i<self.allRateDict.count; i++) {
        
        NSNumber *rateNum = [self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]];
        CGFloat rate = rateNum.floatValue;
        if ([_model.PackageTypeID isEqualToString:@"Sp"]||[_model.PackageTypeID isEqualToString:@"Spn"]||[_model.PackageID isEqualToString:@"Sq"]) {
            if (rate<LS_System.readScore*1.0/100.0) {
                NSLog(@"rate=%f %f",rate,LS_System.readScore*1.0/100.0);
                [wrongQuesIndexArr addObject:@(i)];
                [typeIDArr addObject:_model.PackageTypeID];
                [wrongQuesItemArr addObject:_model.ResItemList[i]];
            }
        } else {
            if (rate<LS_System.listenScore*1.0/100.0) {
                NSLog(@"rate=%f %f",rate,LS_System.listenScore*1.0/100.0);
                [wrongQuesIndexArr addObject:@(i)];
                [typeIDArr addObject:_model.PackageTypeID];
                [wrongQuesItemArr addObject:_model.ResItemList[i]];
            }
        }
    }
    
    LSModelWrongCheckInfo *wrongCheckModel = [LSModelWrongCheckInfo new];
    wrongCheckModel.allAnswerDict = self.allAnswerDict;
    wrongCheckModel.wrongQuesIndexArr = wrongQuesIndexArr;
    wrongCheckModel.wrongQuesModelArr = wrongQuesModelArr;
    wrongCheckModel.wrongQuesItemArr = wrongQuesItemArr;
    wrongCheckModel.typeIDarr = typeIDArr;
    wrongCheckModel.speedLayer = _model.PackageStage;
    
    return wrongCheckModel;
}

- (void)reloadData {
    [self.timeView start];
    [self deleteAllUnZip];
    for (NSInteger i = 0; i<self.vcArray.count; i++) {
        LSResContentVC *vc = self.vcArray[i];
        for (UIView *subview in vc.view.subviews) {
            [subview removeFromSuperview];
        }
    }
    LSResListManager *manager = [[LSResListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"TypeID":_model.PackageTypeID,
                           @"UpdateTime":@""
                           };
    
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(LSModelLSResList *model) {
        
        UIView *view = [selfWeak.view viewWithTag:10000+selfWeak.currentIndex];
        [view removeFromSuperview];
        view = nil;
        
        selfWeak.model = model;
        selfWeak.currentIndex = 0;
        selfWeak.index = 0;
        
        NSString *text = @"";
//        if ([selfWeak.model.PackageTypeID isEqualToString:@"SE"]) {
//            text = [NSString stringWithFormat:@"%@听力训练",text];
//        } else if ([selfWeak.model.PackageTypeID isEqualToString:@"Sp"]||[selfWeak.model.PackageTypeID isEqualToString:@"Spn"]) {
//            text = [NSString stringWithFormat:@"%@朗读训练",text];
//        }
        if (selfWeak.model.PackageStage==1) {
            //text = [NSString stringWithFormat:@"慢速%@",text];
            text = @"第1关";
        } else if (selfWeak.model.PackageStage==2) {
            //text = [NSString stringWithFormat:@"中速%@",text];
            text = @"第2关";
        } else if (selfWeak.model.PackageStage==3) {
           // text = [NSString stringWithFormat:@"快速%@",text];
            text = @"第3关";
        }
        selfWeak.title = text;
        
      //  [selfWeak loadData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            UIWindow *window = [UIApplication sharedApplication].keyWindow;
//            [window addSubview:self.backwhiteView];
            [self.view addSubview:self.backwhiteView];
            [MBProgressHUD showGifAnimationToView:self.view gif:@"LSloading" title:@"试题资源加载中,请稍候..."];
            [selfWeak loadAllFtpResData];
        });
        
    } failuer:^(NSString *error) {
        
    }];
}

#pragma mark - LSReadQuesViewDelegate
- (void)FinishAnswerWordDict:(NSDictionary *)answerDict IsSave:(BOOL)isSave {
    if (!isSave && _currentIndex==self.model.ResItemList.count-1) {
        _isSubmitLast = YES;
    }
    NSLog(@"//////进行保存");
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:answerDict];
    [self.allAnswerDict setObject:dict forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];
    NSString *score = answerDict[@"result"][@"overall"];
    [self.allRateDict setObject:@(score.floatValue/100.00) forKey:[NSString stringWithFormat:@"%ld",_currentIndex+1]];

    NSLog(@"%@",[NSObject objectToJson:answerDict]);
    NSDictionary *resultDict = answerDict[@"result"];
    //句子
    NSMutableArray *senmuarr = [NSMutableArray array];
    NSArray *sentences = resultDict[@"sentences"];
    for (NSInteger i = 0; i<sentences.count; i++) {
        
        NSDictionary *dictionary = sentences[i];
        NSArray *details = dictionary[@"details"];
        NSMutableArray *wordmuarr = [[NSMutableArray alloc] init];
        //单词
        for (NSInteger j = 0; j<details.count; j++) {
            NSDictionary *wordDic = details[j];
            NSDictionary *wordScoreDict = @{@"TotalScore":wordDic[@"overall"],
                                            @"Word":wordDic[@"word"]
                                            };
            [wordmuarr addObject:wordScoreDict];
        }
        
        NSDictionary *senScoreDict = @{@"TotalScore":dictionary[@"overall"],
                                       @"Sentence":dictionary[@"sentence"],
                                       @"WordList":wordmuarr
                                       };
        [senmuarr addObject:senScoreDict];
    }
    
    
    NSDictionary *scoreDict = @{@"TotalScore":resultDict[@"overall"],
                                @"Integrity":NotNull(resultDict[@"integrity"]),
                                @"Fluency":NotNull(resultDict[@"fluency"]),
                                @"Rhythm":NotNull(resultDict[@"rhythm"]),
                                @"Pronunciation":NotNull(resultDict[@"pronunciation"]),
                                @"SentenceList":senmuarr
                                };
    NSInteger count  = 0;
    NSInteger isPass = 0;
    for (NSInteger i = 0; i<self.model.ResItemList.count; i++) {
        CGFloat rate = ((NSNumber*)[self.allRateDict objectForKey:[NSString stringWithFormat:@"%ld",i+1]]).floatValue;
        if (rate>=LS_System.readScore*1.0/100.0) {
            count = count+1;
        }
    }

    if (count == _model.ResItemList.count) {
        isPass = 1;
    }
    
    NSInteger State = 2;
    if (_currentIndex == self.model.ResItemList.count-1) {
        State = 3;
        NSLog(@"self.allRateDict = %@",self.allRateDict);
    }
    if (isSave==YES) {
        State = 1;
    }
    
    LSResItem *item = _model.ResItemList[_currentIndex];
    
    self.dateEnd = [NSDate date];
    NSInteger dur = [self.dateEnd timeIntervalSince1970]-[self.dateStart timeIntervalSince1970];
    NSInteger allDur = [self.dateEnd timeIntervalSince1970]-[self.allstartDate timeIntervalSince1970]+self.timeView.time;
    NSDictionary *saveParam = @{
                                @"StageNo":KGetUserDefaults(@"TestLayer"),
                                @"SchoolID":KGetUserDefaults(@"SchoolID"),
                                @"StuID":DR_UserInfo.UserID,
                                @"QuesID":item.QuesID,
                                @"TypeID":_model.PackageTypeID,
                                @"PackageID":_model.PackageID,
                                @"TotalItemCount":@(1),
                                @"AnswerItemCount":@(1),
                                @"CorrectRate":@(score.floatValue/100.00),
                                @"Score":scoreDict,
                                @"StuAnswer":@[],
                                @"Duration":@(dur),
                                @"State":@(State),
                                @"IsPassed":@(isPass),
                                @"PackageTotalDuration":@(allDur),
                                @"Stage":@(_model.PackageStage),
                                @"ImportKlgCode":item.ImportKlgCode?item.ImportKlgCode:@""
                              
                                };
    LSResPackSaveManager *manager = [[LSResPackSaveManager alloc] init];
    manager.requestParam = saveParam;
    [manager requestSaveResPackWithCompltionSuccess:^(NSString *success) {
        
    } failuer:^(NSString *failure) {
        
    }];
}


#pragma mark - 其他
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //[self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
}

-(void)leftItemsAction:(NSInteger)leftIndex {
    
    [self back];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
   // [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
}

- (void)dealloc {
    NSLog(@"销毁");
}

#pragma mark - pageViewController相关
- (UIScrollView *)findScrollView{
    UIScrollView *scrollView;
    for (id subview in self.pageViewController.view.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            scrollView = subview;
            break;
        }
    }
    return scrollView;
}

- (UIPageViewController *)pageViewController {
    if (!_pageViewController) {
        NSDictionary *options = @{UIPageViewControllerOptionInterPageSpacingKey : @(0)};
        // 根据给定的属性实例化UIPageViewController
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                            options:options];
        // 设置UIPageViewController代理和数据源
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        
        // [self jumpToControllerIndex:0];
        
        // 设置UIPageViewController 尺寸
        _pageViewController.view.frame = CGRectMake(0,0,kWidth, kHeight-kBottomPadding);
        
    }
    return _pageViewController;
}

- (void)initContentViewController {
    self.vcArray = [[NSMutableArray alloc] init];
    
    NSDate *date = [NSDate date];
    for (int i = 0; i<self.model.ResItemList.count; i++) {
        @autoreleasepool {
            LSResContentVC *vc = [[LSResContentVC alloc] init];
            vc.resItem = self.model.ResItemList[i];
            [self.vcArray addObject:vc];
        }
    }
    
    NSLog(@"耗时：%f",[[NSDate date] timeIntervalSince1970] - [date timeIntervalSince1970]);
}

- (void)jumpToControllerIndex:(NSInteger)index {
    [self.view endEditing:YES];
    
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.backwhiteView removeFromSuperview];

    LSResContentVC * initialViewController = self.vcArray[index];
    if (initialViewController.view.subviews.count==0) {
        [self setUpUIwithFatherView:initialViewController.view Index:index];
    }
    for (UIView *view in initialViewController.view.subviews ) {
        if ([view isKindOfClass:[LSListenNewQuesView class]]) {
            
            LSListenNewQuesView *newView = (LSListenNewQuesView*)view;
            [newView startSource];
            
        } else if ([view isKindOfClass:[LSReadNewQuesView class]]) {
            
            LSReadNewQuesView *newView = (LSReadNewQuesView*)view;
            [newView startSource];
        }
    }
    
    self.progressView.index = index+1;
    self.progressView.alpha = 1;
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    
    [_pageViewController setViewControllers:viewControllers
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:YES
                                 completion:nil];
}

#pragma mark - pageViewControll Delegate DataSource
#pragma mark - 数组元素值，得到下标值
- (NSUInteger)indexOfViewController:(LSResContentVC *)viewController {
    
    return [self.model.ResItemList indexOfObject:viewController.resItem];
}


#pragma mark ----- UIPageViewControllerDelegate -----
//开始滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    _pendingViewController = (LSResContentVC*)pendingViewControllers.lastObject;
    
    [self.view endEditing:YES];
}

//结束滚动或翻页的时候触发
- (void)pageViewController:(UIPageViewController *)pageViewController
        didFinishAnimating:(BOOL)finished
   previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers
       transitionCompleted:(BOOL)completed {
    
    NSInteger index = [self indexOfViewController:_pendingViewController];//滚动结束后的index
    NSLog(@"当前的index是：%ld",(long)index);
    self.progressView.index = index+1;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_pendingViewController.view.subviews.count==0) {
            [self setUpUIwithFatherView:_pendingViewController.view Index:index];
        }
    });
}

#pragma mark ----- UIPageViewControllerDataSource -----
#pragma mark 返回上一个ViewController对象
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSResContentVC *)viewController];
    
    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }
    index--;
    // 返回的ViewController，将被添加到相应的UIPageViewController对象上。
    // UIPageViewController对象会根据UIPageViewControllerDataSource协议方法,自动来维护次序
    // 不用我们去操心每个ViewController的顺序问题
    return self.vcArray[index];
    
}

#pragma mark - 返回下一个ViewController对象

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    [self.view endEditing:YES];
    
    NSUInteger index = [self indexOfViewController:(LSResContentVC*)viewController];
    
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    
    if (index == [self.model.ResItemList count]) {
        return nil;
    }
    
    return self.vcArray[index];
}



@end


@implementation LSResContentVC



@end


@implementation LSModelWrongCheckInfo



@end
